package cn.edu.dgut.sai.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.Properties;

/**
 * 企业级软件开发-实训课程：Spring Boot 2.x
 *
 * @author 黎志雄
 * 2019-9-17
 *
 * {@link EnvironmentPostProcessor}接口的实现类用于自定义{@link Environment},在application context刷新上下文之前。
 *
 * 必须在{@code META-INF/spring.factories}中注册EnvironmentPostProcessor接口的实现类。
 * 如：
 * org.springframework.boot.env.EnvironmentPostProcessor=cn.edu.dgut.sai.config.SaiPropertiesPostProcessor
 */
public class SaiPropertiesPostProcessor implements EnvironmentPostProcessor {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment,
                                       SpringApplication application) {
		// 读取自定义的sai.properties文件
		ClassPathResource resource = new ClassPathResource("sai.properties");
		if (resource.exists()) {
			PropertySource<?> source = getPropertySource(resource);
			environment.getPropertySources().addLast(source);
		}
	}

	// 构造PropertiesPropertySource
	// Environment默认有两个属性源，JVM 与 系统环境变量。
	// 添加了 自定义的属性源后，就可以使用Environment.getProperty()获取指定属性名的属性值，Environment会查找所有注册的属性源。
	private PropertySource<?> getPropertySource(ClassPathResource resource) {
		try {
			Properties properties = new Properties();
			properties.load(resource.getInputStream());
			return new PropertiesPropertySource("sai", properties);
		}
		catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

}
